package com.xc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.enums.BizCodeEnum;
import com.xc.enums.SendCodeEnum;
import com.xc.feign.CouponFeignService;
import com.xc.interceptor.LoginInterceptor;
import com.xc.mapper.UserMapper;
import com.xc.model.LoginUser;
import com.xc.model.UserDO;
import com.xc.request.UserLoginRequest;
import com.xc.request.UserRegisterRequest;
import com.xc.service.NotifyService;
import com.xc.service.UserService;
import com.xc.utils.CommonUtil;
import com.xc.utils.JWTUtil;
import com.xc.utils.JsonData;
import com.xc.utils.StringUtils;
import com.xc.vo.NewUserCouponRequest;
import com.xc.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author xingchen
 * @create 2021/10/29 10:24
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * * 邮箱验证码校验
     * * 密码加密（TODO）
     * * 账号唯一性检查（TODO）
     * * 插入数据库
     * * 新注册用用户福利发放（TODO）
     *
     * @param registerRequest
     * @return
     */
    @Override
    public JsonData register(UserRegisterRequest registerRequest) {

        boolean checkCode = false;
        if (StringUtils.isNotBlank(registerRequest.getCode())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER,
                    registerRequest.getMail(), registerRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(registerRequest, userDO);
        userDO.setCreateTime(new Date());
        userDO.setSlogan("人生需要动态规划，学习需要贪心算法");
        //设置密码 TODO
        //生成密钥 盐
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));

        //密码+盐处理
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);

        //账号唯一性检查 TODO
        if (checkUnique(userDO.getMail())) {
            //插入数据库  获取操作结果
            int rows = userMapper.insert(userDO);
            log.info("rows{},注册成功:{}", rows, userDO.toString());

            //新用户注册成功，初始化信息，发放福利等 //TODO
            userRegisterInitTask(userDO);
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }

    }

    /**
     * 1、根据Mail去找有没有记录
     * 2、有的话，则用秘钥+用户传递的明文密码，进行加密，再和数据库的密文进行匹配
     *
     * @param userLoginRequest
     * @return
     */
    @Override
    public JsonData login(UserLoginRequest userLoginRequest) {

        List<UserDO> userDOList = userMapper.selectList(new QueryWrapper<UserDO>().eq("mail", userLoginRequest.getMail()));

        if (userDOList != null && userDOList.size() == 1) {
            //已经注册
            UserDO userDO = userDOList.get(0);
            String cryptPwd = Md5Crypt.md5Crypt(userLoginRequest.getPwd().getBytes(), userDO.getSecret());
            if (cryptPwd.equals(userDO.getPwd())) {
                //登录成功,生成token TODO

                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);

            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }

        } else {
            //未注册
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);

        }
    }

    /**
     * 查询用户详情
     *
     * @return
     */
    @Override
    public UserVO findUserDetail() {

        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", loginUser.getId()));
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userDO, userVO);
        return userVO;
    }

    /**
     * 校验用户账号唯一
     *
     * @param mail
     * @return
     */
    private boolean checkUnique(String mail) {

        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", mail);
        List<UserDO> list = userMapper.selectList(queryWrapper);
        return list.size() > 0 ? false : true;
    }


    /**
     * 用户注册，初始化福利信息  TODO
     *
     * @param userDO
     */
    private void userRegisterInitTask(UserDO userDO) {

        NewUserCouponRequest request = new NewUserCouponRequest();
        request.setName(userDO.getName());
        request.setUserId(userDO.getId());
        JsonData jsonData = couponFeignService.addNewUserCoupon(request);
        log.info("发放新用户注册优惠券: {},结果:{}", request.toString(), jsonData.toString() );
    }


}
